package com.bawei.yangzongcai___chenmei.MVC.base;

import android.os.Handler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * create by ertu
 * create on 2021/7/12
 *     功能实现：封装OKhttp单例类
 */
public class HttpMannoss {
    public  static HttpMannoss mannoss;//本类
    public  static Handler handler;//线程
    public  static OkHttpClient client;//协议

    //调用放大
    public  static  HttpMannoss getMannoss()
    {
        if (mannoss==null)
        {
         mannoss =   new HttpMannoss();
        }
        return mannoss;
    }

    //添加拦截器
    public HttpMannoss()
    {
        client = new OkHttpClient.Builder()
                .addInterceptor(new HoshDoootoTion())
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .build();
        handler = new Handler();
    }


    //封装doget方法
    public  void doGet(String ugetl, final MayCallback callback)
    {
        client.newCall(new Request.Builder()
                .url(ugetl)
                .build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback!=null)
                {
                    callback.fial(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.code()==200)
                {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                         if (callback!=null)
                         {
                             callback.suuess(response);
                         }
                        }
                    });
                }else {
                    if (callback!=null)
                    {
                        callback.fial(response.message());
                    }
                }
            }
        });
    }


    public interface MayCallback
    {
        void suuess(Response response);
        void fial(String smg);
    }


}
